import React, { useState, useEffect } from 'react'
import { Image, Text, View, navigateTo } from 'remax/one'
import { usePageEvent } from 'remax/macro'
import {
  cloud,
  Swiper,
  SwiperItem,
  ScrollView,
  makePhoneCall,
  showModal,
} from 'remax/wechat'
import { Row, Space, Tag } from 'annar'
import dayjs from 'dayjs'
import useCloud from '@/hooks/use-cloud'
import useLocation from '@/hooks/use-location'
import styles from './index.css'

const PromotionCastItem = ({
  _id,
  promotion: { name, imgUrls, price, originalPrice, quota, store },
  currQuota,
}: WBG.PromotionCast) => {
  const currDate = dayjs().format('YYYY-MM-DD')

  return (
    <View
      className={styles.item}
      hoverClassName="hover"
      onTap={() => {
        navigateTo({ url: `/pages/promotion/index?_id=${_id}` })
      }}
    >
      <Image className={styles.itemImg} src={imgUrls[0]} mode="widthFix" />
      <Space className={styles.itemDesc} direction="vertical" size={12}>
        <View className="large-text">{name}</View>
        <Space align="center" size={12}>
          <Text className="large-text alarm-text">￥{price}</Text>
          <Text className="deleted-text">￥{originalPrice}</Text>
          <Tag className="no-border" color="red">
            {Math.round((price / originalPrice) * 100) / 10} 折
          </Tag>
        </Space>
        <Row justify="space-between" align="middle">
          <View className="small-text">
            距离您 {Math.round((store.distance / 1000) * 10) / 10} 公里
          </View>
          <Text className="small-text">
            剩余{' '}
            <Text className="alarm-text">
              {currQuota[currDate] || 0}/{quota}
            </Text>
          </Text>
        </Row>
      </Space>
    </View>
  )
}

export default () => {
  const [adbanners, setAdbanners] = useState([])
  useEffect(() => {
    ;(async () => {
      const { data } = await cloud.database().collection('adbanner').get()
      setAdbanners(data)
    })()
  }, [])

  const { location } = useLocation()
  const [tag, setTag] = useState('推荐')
  const { data, mutate } = useCloud(location ? 'list-promotion-cast' : null, {
    location,
    tags: tag && tag !== '推荐' ? [tag] : undefined,
  })
  const [loading, setLoading] = useState(false)

  usePageEvent('onShareAppMessage', async () => {
    return {}
  })

  if (!location) {
    return null
  }

  return (
    <>
      <Swiper
        className={styles.topArea}
        indicatorDots={adbanners.length > 1}
        autoplay
        circular
      >
        {adbanners.map(({ imgUrl }, i) => (
          <SwiperItem key={i}>
            <Image className={styles.topImg} src={imgUrl} mode="aspectFill" />
          </SwiperItem>
        ))}
      </Swiper>
      <View className={styles.tagArea}>
        <Row
          className={styles.fullHeight}
          justify="space-between"
          align="middle"
        >
          <Row align="middle">
            {['推荐'].map(v => (
              <Text
                key={v}
                className={tag === v ? styles.tagActiveText : styles.tagText}
                onTap={() => setTag(v)}
              >
                {v}
              </Text>
            ))}
          </Row>
          <View
            style={{
              display: 'flex',
              flexDirection: 'column',
              justifyContent: 'space-around',
              alignItems: 'center',
            }}
            onTap={async () => {
              const day = dayjs().day()
              const time = dayjs().format('HH:mm')
              if (day <= 0 || day >= 6 || time < '09:30' || time > '18:30') {
                const { cancel } = await showModal({
                  title: '拨号提示',
                  content:
                    '服务时间为工作日9:30-18:30，当前不在服务时间内，是否继续拨打？',
                })
                if (cancel) {
                  return
                }
              }
              makePhoneCall({ phoneNumber: '01057076202' })
            }}
          >
            <Image
              src={'/images/service.png'}
              style={{ width: '40px' }}
              mode="widthFix"
            />
            <Text className="small-text">客服</Text>
          </View>
        </Row>
      </View>
      <ScrollView
        className={styles.mainArea}
        scrollY
        refresherEnabled
        refresherTriggered={loading}
        onRefresherRefresh={async () => {
          setLoading(true)
          await mutate()
          setLoading(false)
        }}
      >
        {data &&
          (data.length ? (
            <View className={styles.itemArea}>
              {data.map((v: any) => (
                <PromotionCastItem key={v._id} {...v} />
              ))}
            </View>
          ) : (
            <View className="empty-view small-text">您附近暂时没有活动</View>
          ))}
      </ScrollView>
    </>
  )
}
